<template>
    <n-grid y-gap="2" :cols="24">
        <n-gi :span="24">
            <n-grid :cols="24">
                <n-gi :span="12">
                    <n-space>
                        <n-button type="info" size="small" @click="addUrls">添加</n-button>
                        <n-button type="info" size="small" @click="askTest">ask</n-button>
                        <n-button type="success" size="small" @click="adminClassDlgVisible = true">分类管理</n-button>
                        <n-input v-model:value="searchInput" type="text" size="small" placeholder="输入关键字" 
                            @input="handleInput" clearable />
                    </n-space>
                    
                </n-gi>
                <n-gi :span="12" v-if="allClass.length<=6">
                    <n-space class="right-top-class-buttons">
                        <n-tag type="success" size="small" round @click="changeClass('all')">全部</n-tag>
                        <n-tag type="success" size="small" round v-for="u_class in allClass" :key="u_class.c_id" 
                            @click="changeClass(u_class.c_id)">
                            {{ u_class.c_name }}
                        </n-tag>
                    </n-space>
                </n-gi>
                <n-gi :span="12" v-if="allClass.length>6" style="text-align: right;">
                    <n-popselect
                        v-model:value="rightTopClassValue"
                        :options="rightTopClassOptions"
                        size="medium"
                        scrollable
                    >
                        <n-button style="margin-right: 8px">
                            {{ rightTopClassValue || 'Popselect' }}
                        </n-button>
                    </n-popselect>
                </n-gi>
            </n-grid>
        </n-gi>
        <n-gi :span="24" >
            <!-- <vxe-table
                border
                :max-height="tableHeight" 
                :min-height="tableHeight"
                show-overflow
                class="mytable-scrollbar"
                :data="tableData">
                <vxe-column type="seq" width="50"></vxe-column>
                <vxe-column field="address_id" title="操作" width="100">
                    <template #default="{row}">
                        <n-button type="info" size="tiny" @click="editUrl(row)">修改</n-button>
                        <n-button type="error" size="tiny" @click="delUrl(row)">删除</n-button>
                    </template>
                </vxe-column>
                <vxe-column field="address_url" title="网址">
                    <template #default="{row}">
                        <p @click="openUrl(row)" style="cursor:pointer;font-weight:bold;">{{ row.address_title }}</p>
                        <p style="font-size: 12px;">{{ row.address_url }}</p>
                    </template>
                </vxe-column>
            </vxe-table> -->
            <n-data-table
                :columns="createColumns"
                :data="tableData"
                size="small"
                :max-height="tableHeight"
                :min-height="tableHeight"
            ></n-data-table>
        </n-gi>
    </n-grid>
    <n-modal 
        v-model:show="editDlgVisible" 
        preset="dialog" 
        :mask-closable="false"
        title="新增"
        :on-after-leave="closeEditDlgEnv">
        <template #header>
        <div>新增</div>
        </template>
        <div>
            <n-form
                ref="urlFormRef"
                :model="urlForm"
                :rules="urlRules"
                label-placement="left"
                label-width="auto"
                require-mark-placement="right-hanging"
                size="small">
                <n-form-item label="标题" path="url.address_title">
                    <n-input 
                        v-model:value="urlForm.url.address_title" 
                        maxlength="128" 
                        show-count 
                        clearable 
                        placeholder="请输网站标题"/>
                </n-form-item>
                <n-form-item label="地址" path="url.address_url">
                    <n-input 
                        v-model:value="urlForm.url.address_url"
                        type="textarea"
                        :autosize="{minRows:2,maxRows:4}"
                        placeholder="请输网址"
                    />
                </n-form-item>
                <n-form-item label="分类" path="url.c_id">
                    <n-select
                        v-model:value="urlForm.url.c_id"
                        label-field="c_name"
                        value-field="c_id"
                        :options="allClass"
                    />
                </n-form-item>
            </n-form>
        </div>
        <template #action>
            <n-space>
                <n-button type="info" size="small" @click="saveUrlForm">保存</n-button>
                <n-button size="small" @click="editDlgVisible = false">取消</n-button>
            </n-space>
        </template>
    </n-modal>
    <n-modal v-model:show="adminClassDlgVisible"
        preset="dialog"
        title="分类管理"
        >
        <div :style="computedCss()">
            <n-grid y-gap="2" :cols="24">
            <n-gi :span="24">
                <n-button type="info" size="small" @click="editClassDlgVisible = true">新增</n-button>
            </n-gi>
            <n-gi :span="24">
                <n-data-table
                    :columns="createClassColumns"
                    :data="allClass"
                    size="small"
                ></n-data-table>
            </n-gi>
        </n-grid>
            
        </div>
    </n-modal>
    <n-modal v-model:show="editClassDlgVisible" 
        title="分类"
        preset="dialog"
        :mask-closable="false" 
        :on-after-leave="closeEditClassDlgEnv">
        
        <n-form
            ref="classFormRef"
            :model="classForm"
            :rules="classRules"
            label-placement="left"
            label-width="auto"
            require-mark-placement="right-hanging"
            size="small">
            <n-form-item label="分类名称" path="class.c_name">
                <n-input v-model:value="classForm.class.c_name" maxlength="12" show-count autofocus placeholder="输入分类名称"/>
            </n-form-item>
        </n-form>
        <template #action>
            <n-space>
                <n-button type="info" size="small" @click="editClassHandle">保存</n-button>
                <n-button size="small" @click="editClassDlgVisible = false">取消</n-button>
            </n-space>
        </template>
    </n-modal>
</template>
<script setup>
import {ref,reactive,h,watch} from 'vue';
import { useMessage,NButton,useDialog,NSpace,NText,NGrid,NGi } from "naive-ui";

import { invoke } from "@tauri-apps/api/core";
import {open } from "@tauri-apps/plugin-shell";
import {sendNotification,isPermissionGranted, requestPermission} from "@tauri-apps/plugin-notification";
import {ask} from "@tauri-apps/plugin-dialog";

const message = useMessage();
const dialog = useDialog();

const urlFormRef = ref(null);

let searchInput = ref('');
const tableHeight = ref(300);
let tableData = ref([]);
let allClass = ref([]);
const editDlgVisible = ref(false);
const delDlgVisible = ref(false);
const adminClassDlgVisible =  ref(false);
const editClassDlgVisible = ref(false);

const cssScreenWidth = window.innerWidth;
const cssScreenHeight = window.innerHeight;
const urlForm = ref({
    url:{
        address_title: '',
        address_url: '',
        c_id:'',
        address_id: ''
    }
});
const urlRules = {
    url:{
        address_title:{
            required: true,
            trigger: 'blur',
            message: "标题不能为空!"
        },
        address_url:{
            required: true,
            trigger: 'blur',
            message: "地址不能为空!"
        },
        c_id:{
            required: true,
            trigger: ['blur','change'],
            message: "请选择分类！"
        }
    }
}

const classForm = ref({
    class:{
        c_id: '',
        c_name:''
    }
});
const classRules = {
    class:{
        c_name:{
            required: true,
            trigger: ['blur','change'],
            message: "分类名称不能为空!"
        }
    }
}
let delObj = {row:{},type:'',msg:''};
let currentSelectClassId = 'all';
const createClassColumns = ref([
    {
        title: '分类名称',
        key: 'c_name',
    },{
        title: '操作',
        key: 'c_id',
        width: 120,
        render(row){
            return [
                h(NButton,{
                    size: 'small',
                    type: 'info',
                    style:{
                        marginRight: '3px'
                    },
                    onClick: ()=>editClass(row)
                },{
                    default: ()=>"修改"
                }),
                h(NButton,{
                    size: 'small',
                    type: 'error',
                    onClick: ()=> delClass(row)
                },{
                    default: ()=> "删除"
                })
            ]
        }
    }
])
const createColumns=ref([
    {
        title:'操作',
        key:'address_id',
        width:120,
        render(row){
            return [
            h(NButton,{
                size: "small",
                type: 'info',
                style: {
                    marginRight: '3px'
                },
                onClick: ()=>editUrl(row)
            },()=> "修改"),
            h(NButton,{
                size: "small",
                type: 'error',
                onClick: ()=> delUrl(row)
            },()=>"删除")
            ]
        }
    },{
        title: '标题',
        key: 'address_title',
        ellipsis:{
            tooltip: true
        },
        render(row){
            return h(NGrid,{cols:24},{default:()=>[
                h(NGi,{span:24},{default:()=>h(NText,{onClick:()=>openUrl(row),style:{cursor:'pointer',fontWeight:'bold'}},{default:()=>row.address_title})}),
                h(NGi,{span:24},{default:()=>h(NText,{style:{fontSize:'12px'}},{default:()=>row.address_url})})
            ]})
        }
    }
]);

const rightTopClassValue = ref(null);
const rightTopClassOptions = ref([]);

getAllUrls();
getClass();

window.addEventListener('resize',()=>{
    computedTableHight();
});

tableHeight.value = window.innerHeight-80;
function computedTableHight(){
    tableHeight.value = window.innerHeight-80;
}
function computedCss(){
    return {'height': (window.innerHeight-200)+'px','overflow-y': 'auto'}
}

function handleInput(v){
    getAllUrls();
}
function delClass(row){
    delObj.row = row;
    delObj.msg = "确定要删除该分类吗？如果分类中有对应的收藏内容，也会一并删除!";
    delObj.type = 'class';

    //delDlgVisible.value = true;
    dialog.warning({
        title: '删除',
        content: delObj.msg,
        positiveText: "确定",
        negativeText: "取消",
        onPositiveClick: ()=>{
            delUrlOrClassHandle();
        }
    })
}
function editClass(row){
    classForm.value.class.c_id = row.c_id;
    classForm.value.class.c_name = row.c_name;
    editClassDlgVisible.value = true;
}
async function editClassHandle(){
    let ret = await invoke('save_class',{cId:classForm.value.class.c_id, cName:classForm.value.class.c_name});
    if(ret){
        editClassDlgVisible.value = false;
        message.success(classForm.value.class.c_id?'修改成功!':"保存成功!");
        classForm.value.class.c_id = '';
        classForm.value.class.c_name = '';
        getClass();
    }
}
async function getClass() {
    allClass.value = await invoke("get_all_url_class");
    if(allClass.value.length>0){
        urlForm.value.url.c_id = allClass.value[0].c_id;
    }
    rightTopClassOptions.value = [];
    allClass.value.forEach(v=>{
        rightTopClassOptions.value.push({
            label: v.c_name,
            value: v.c_id
        });
    }); 
}
let addUrls = ()=>{
    editDlgVisible.value = true;

    //console.log(`CSS Screen width: ${cssScreenWidth}`);
    //console.log(`CSS Screen height: ${cssScreenHeight}`);
}
async function getAllUrls(){
    tableData.value = await invoke("get_all_url",{cId:currentSelectClassId,keyWord:searchInput.value});
}
async function editUrl(row){
    /*let permissionGranted = await isPermissionGranted();
    if(!permissionGranted){
        const permission = await requestPermission();
        permissionGranted = permission === 'granted';
    }
    if(permissionGranted){
        sendNotification({title:'日程提醒',body:'这是我的第一个通知!'});
        message.success('已经发送通知.');
    }else{
        message.success('无通知发送权限.');
    }*/
    urlForm.value.url.address_title = row.address_title;
    urlForm.value.url.address_url = row.address_url;
    urlForm.value.url.c_id = row.c_id;
    urlForm.value.url.address_id = row.address_id;

    editDlgVisible.value = true;
}
async function delUrlOrClassHandle(){
    let ret = false;
    if(delObj.type == 'url'){
        ret = await invoke('del_url_by_id',{id:delObj.row.address_id});
    }else{
        ret = await invoke('del_class_by_id',{id:delObj.row.c_id});
    }
    
    if(ret){
        delDlgVisible.value = false;
        message.success('删除成功!');
        if(delObj.type =='url'){
            getAllUrls();
        }else{
            getClass();
        }
        delObj = {row:{},type:'',msg:''};
    }
}
async function delUrl(row){
    delObj.row = row;
    delObj.type = 'url';
    delObj.msg = '确定要删除吗?';
    dialog.warning({
        title: '删除',
        content: '确定要删除吗?',
        positiveText: '确定',
        negativeText: '取消',
        onPositiveClick: ()=>{
            delUrlOrClassHandle();
        }
    });
    //delDlgVisible.value = true;
    
    // let permissionGranted = await isPermissionGranted();
    // if(!permissionGranted){
    //     const permission = await requestPermission();
    //     permissionGranted = permission === 'granted';
    // }
    // if(permissionGranted){
    //     sendNotification('这是我的第一个通知!');
    // }else{
    //     message.success('无通知发送权限.');
    // }

    /*const yes = await ask('确定要执行这个操作吗？',{title: "应用名称", type:"warning"});
    console.log(yes);*/
}
function openUrl (row){
    open(row.address_url);
}
function closeEditDlgEnv(){
    urlForm.value.url.address_title = '';
    urlForm.value.url.address_url = '';
    urlForm.value.url.address_id = '';
    urlForm.value.url.c_id = '';
    
    if (currentSelectClassId != 'all'){
        urlForm.value.url.c_id = currentSelectClassId;
    }else{
        if(allClass.value.length>0){
            urlForm.value.url.c_id = allClass.value[0].c_id;
        }
    }
    
}
function closeEditClassDlgEnv(){
    classForm.value.class.c_id = '';
    classForm.value.class.c_name = '';
}
async function saveUrlFormHandle(){
    let ret = await invoke('save_url_form',{
        addressId:urlForm.value.url.address_id,
        addressTitle: urlForm.value.url.address_title,
        addressUrl: urlForm.value.url.address_url,
        cId:urlForm.value.url.c_id
    });
    console.log(ret);
    if(ret){
        message.success('保存成功!');
        editDlgVisible.value = false;
        getAllUrls();
    }else{
        message.error('保存失败!');
    }
}
function saveUrlForm(e){
    e.preventDefault();
    urlFormRef.value?.validate((errors)=>{
        if(errors){
            console.log(errors);
        }else{
            saveUrlFormHandle();
        }
    })
    
}
function changeClass(class_id){
    currentSelectClassId = class_id;
    getAllUrls();
}
async function askTest(){
    const answer = await ask('This action cannot be reverted. Are you sure?', {
        title: 'Tauri',
        kind: 'warning',
    });

    console.log(answer);
}
</script>
<style scss scoped>
.mytable-scrollbar {
  ::-webkit-scrollbar {
    width: 8px;
    height: 8px;
  }
  ::-webkit-scrollbar-thumb {
    border-radius: 4px;
  }
}

/** 默认模式 */
[data-vxe-ui-theme="light"] {
  .mytable-scrollbar {
    ::-webkit-scrollbar-track,
    ::-webkit-scrollbar-corner {
      background-color: #FFFFFF;
    }
    ::-webkit-scrollbar-thumb {
      background-color: #bfbfbf;
    }
    ::-webkit-scrollbar-thumb:hover,
    ::-webkit-scrollbar-thumb:active {
      background-color: #787878;
    }
  }
}

/** 暗黑模式 */
[data-vxe-ui-theme="dark"] {
  .mytable-scrollbar {
    ::-webkit-scrollbar-track,
    ::-webkit-scrollbar-corner {
      background-color: #151518;
    }
    ::-webkit-scrollbar-thumb {
      background-color: #bfbfbf;
    }
    ::-webkit-scrollbar-thumb:hover,
    ::-webkit-scrollbar-thumb:active {
      background-color: #A3A6AD;
    }
  }
}
</style>